<?php

namespace App\Http\Lib;

use Illuminate\Http\Request;

class Parser
{
    /**
     * The key.
     *
     * @var string
     */
    protected static $key = 'token';
    
    /**
     * The header name.
     *
     * @var string
     */
    protected static $header = 'authorization';
    
    /**
     * The header prefix.
     *
     * @var string
     */
    protected static $prefix = 'bearer';
    
    /**
     * Try to parse the token from the request.
     *
     * @param  \Illuminate\Http\Request  $request
     *
     * @return false|string
     */
    public static function parseToken(Request $request) {
        $header = $request->headers->get(self::$header) ?: self::fromAltHeaders($request);
        
        if ($header && preg_match('/'.self::$prefix.'\s*(\S+)\b/i', $header, $matches)) {
            return $matches[1];
        } else if ($request->query(self::$key)) {
            return $request->query(self::$key);
        } else {
            return false;
        }
    }
    
    /**
     * Attempt to parse the token from some other possible headers.
     *
     * @param  \Illuminate\Http\Request  $request
     *
     * @return null|string
     */
    protected static function fromAltHeaders(Request $request)
    {
        return $request->server->get('HTTP_AUTHORIZATION') ?: $request->server->get('REDIRECT_HTTP_AUTHORIZATION');
    }
    
    /**
     * Set the key.
     *
     * @param  string  $key
     *
     * @return $this
     */
    public static function setKey($key)
    {
        $this->key = $key;
    
        return $this;
    }
    
    /**
     * Get the key.
     *
     * @return string
     */
    public static function getKey()
    {
        return $this->key;
    }
    
    /**
     * Set the header name.
     *
     * @param  string  $headerName
     *
     * @return $this
     */
    public static function setHeaderName($headerName)
    {
        $this->header = $headerName;
    
        return $this;
    }
    
    /**
     * Set the header prefix.
     *
     * @param  string  $headerPrefix
     *
     * @return $this
     */
    public static function setHeaderPrefix($headerPrefix)
    {
        $this->prefix = $headerPrefix;
    
        return $this;
    }
}